#!/bin/bash
# 脚本名称：bigdata-A
# 功能：容器网络管理工具（支持启停、日志记录、网卡绑定）

# 配置区, 定义容器和网卡映射关系（格式：容器名:宿主机网卡:容器IP）
CONFIG=(
  "master:eth1:192.168.100.101/24"
  "slave1:eth2:192.168.100.102/24"
  "slave2:eth3:192.168.100.103/24"
)
GATEWAY="192.168.100.2"
LOG_FILE="/var/log/xfcloud.log"
OPERATION="start"  # 默认操作
TARGET_CONTAINERS=()  # 目标容器列表

# 初始化日志系统
init_logging() {
  sudo mkdir -p $(dirname "$LOG_FILE")
  sudo touch "$LOG_FILE" && sudo chmod 644 "$LOG_FILE"
  exec > >(tee -a "$LOG_FILE") 2>&1
}

# 彩色输出函数
color_echo() {
  local color=$1 msg=$2
  case $color in
    red)    echo -e "\033[31m$msg\033[0m" ;;
    green)  echo -e "\033[32m$msg\033[0m" ;;
    yellow) echo -e "\033[33m$msg\033[0m" ;;
    *)      echo -e "$msg" ;;
  esac
}

# 关键信息高亮
highlight_critical() {
  while read -r line; do
    if [[ $line =~ ERROR|FAILED ]]; then
      color_echo red "$line"
    elif [[ $line =~ SUCCESS|READY ]]; then
      color_echo green "$line"
    else
      echo "$line"
    fi
  done
}

# 参数解析
parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --start|--stop)
        OPERATION="${1#--}"
        shift
        ;;
      *)
        TARGET_CONTAINERS+=("$1")
        shift
        ;;
    esac
  done
}

# 检查宿主机网卡
check_interfaces() {
  for entry in "${CONFIG[@]}"; do
    IFS=':' read -ra cfg <<< "$entry"
    if ! ip link show "${cfg[1]}" &>/dev/null; then
      echo "ERROR: 宿主机网卡 ${cfg[1]} 不存在" >&2
      return 1
    fi
  done
}

# 容器操作核心逻辑
handle_container() {
  local container=$1
  # 获取容器配置
  for entry in "${CONFIG[@]}"; do
    IFS=':' read -ra cfg <<< "$entry"
    [[ "${cfg[0]}" == "$container" ]] || continue
    
    local iface=${cfg[1]} ip_addr=${cfg[2]}
    
    case $OPERATION in
      start)
        # 启动容器
        if ! docker ps -a --format '{{.Names}}' | grep -qx "$container"; then
          echo "ERROR: 容器 $container 不存在" >&2
          return 1
        fi
        
        docker start "$container" >/dev/null || return 1
        
        # 绑定网卡
        local pid=$(docker inspect -f '{{.State.Pid}}' "$container")
        mkdir -p /var/run/netns
        ln -sf "/proc/$pid/ns/net" "/var/run/netns/$container"
        
        ip link set "$iface" netns "$container"
        ip netns exec "$container" ip link set dev "$iface" up
        ip netns exec "$container" ip addr add "$ip_addr" dev "$iface"
        ip netns exec "$container" ip route add default via "$GATEWAY"
        
        echo "SUCCESS: $container 已启动并绑定网卡 $iface" 
        ;;
        
      stop)
        # 停止容器
        docker stop "$container" >/dev/null || return 1
        
        # 清理网卡（移回宿主机）
        ip netns exec "$container" ip link set dev "$iface" down
        ip netns exec "$container" ip link set "$iface" netns 1
        
        # 删除网络命名空间
        ip netns del "$container" 2>/dev/null
        
        echo "SUCCESS: $container 已停止并解绑网卡" 
        ;;
    esac
    return 0
  done
  
  echo "ERROR: 未找到容器 $container 的配置" >&2
  return 1
}

# 主流程控制
main() {
  init_logging
  parse_args "$@"
  
  echo "====== 操作开始: $(date) ======" | highlight_critical
  
  # 确定目标容器
  local containers=()
  if [[ ${#TARGET_CONTAINERS[@]} -eq 0 ]]; then
    containers=("${CONFIG[@]%%:*}")
  else
    containers=("${TARGET_CONTAINERS[@]}")
  fi

  # 前置检查
  check_interfaces | highlight_critical || exit 1

  # 遍历操作
  for container in "${containers[@]}"; do
    if handle_container "$container"; then
      color_echo green "[OK] $container 操作成功"
    else
      color_echo red "[FAIL] $container 操作失败"
      exit 1
    fi
  done
  
  echo "====== 操作结束: $(date) ======" | highlight_critical
}

# 执行入口
main "$@"